package _5thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @Author wangzhen
 * @Date 2022-06-08 22:45
 **/
public class ConditionTest {

    static int size=0;
    public static void main(String[] args){

        Thread prod=new Thread("生产者"){

            @Override
            public void run() {

                for(int i=1;i<=10;i++){
                    prod();
                }
            }
        };

        //两个消费者线程消费10个包子
        Thread thread1=new Thread("消费者1号"){

            @Override
            public void run() {

                while (true){
                    consume();
                }

            }
        };


        Thread thread2=new Thread("消费者2号"){

            @Override
            public void run() {

                while (true){
                    consume();
                }

            }
        };


        thread1.start();
        thread2.start();
        prod.start();
    }

    /**
     * 生产方法
     */
    public synchronized static void prod(){

        try {

            size++;
            Thread.sleep(150);
            ConditionTest.class.notifyAll();
            System.out.println(Thread.currentThread().getName()+"生产了1个,当前剩余"+size);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    /**
     * 消费方法
     */
    public synchronized static void consume(){

        try {


            //查看是否有剩余，若没有，则等待生产者生产
            if(size<=0){
                ConditionTest.class.wait();//进入阻塞等待状态
            }

            size-=1;
            System.out.println(Thread.currentThread().getName()+"消费了1个,当前剩余"+size);
        } catch (Exception e) {
            e.printStackTrace();

        }finally {
        }

    }

}
